import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.InputMismatchException;

public class FrontDesk extends User {
    private List<Ticket> ticketList;
    private Scanner scanner;
    public FrontDesk(String userId, String username, String password, String registerTime, String phone, String userType) {
        super(userId, username, password, registerTime, phone, "前台");
        this.ticketList = new ArrayList<>();
        this.scanner = new Scanner(System.in);
    }

    @Override
    public void login() {
        int chance = 3;
        int attempt = 0;
        while (attempt < chance) {
            System.out.print("请输入前台用户名：");
            String name = scanner.next().trim();
            System.out.print("请输入密码：");
            String password = scanner.next().trim();
            User user = null;
            for (User u : UserList.getAllUsers()) {
                if (u.getUserName().equals(name) && u.getUserType().equals("前台")) {
                    user = u;
                    break;
                }
            }
            if (user != null && user.getUserPassword().equals(password)) {
                Log.info(name, "登录系统", "前台登录成功");
                System.out.println("登录成功！欢迎您，" + user.getUserName() + "前台！");
                show();
                return;
            } else {
                attempt++;
                int remaining = chance - attempt;
                Log.warning(name, "登录失败", "用户名或密码错误，剩余" + remaining + "次机会");
                System.out.println("用户名/密码错误！剩余" + remaining + "次机会。");
            }
        }
        Log.warning("未知用户", "登录失败", "前台登录失败次数超限");
        System.out.println("登录失败次数过多，退出登录。");
    }

    @Override
    public void exit() {
        Log.info(getUserName(), "退出系统", "前台返回主菜单");
        System.out.println("已退出前台系统，返回主菜单");
    }

    @Override
    public void show() {
        while (true) {
            System.out.println("\n=======前台操作菜单=========");
            System.out.println("1------->正在上映影片信息");
            System.out.println("2------->场次信息查询");
            System.out.println("3------->售票");
            System.out.println("4------->退票");
            System.out.println("5------->场次座位信息查询");
            System.out.println("6------->退出");
            System.out.print("请输入1-6的数字选择功能：");
            int choice;
            try {
                choice = Integer.parseInt(scanner.next().trim());
            } catch (NumberFormatException e) {
                System.out.println("输入错误，请输入数字！");
                Log.error(getUserName(), "菜单选择", e);
                continue;
            }
            switch (choice) {
                case 1:
                    listPlayingMovies();
                    break;
                case 2:
                    listShows();
                    break;
                case 3:
                    sellTicket();
                    break;
                case 4:
                    refundTicket();
                    break;
                case 5:
                    listSeatInfo();
                    break;
                case 6:
                    exit();
                    return;
                default:
                    System.out.println("输入无效，请重新输入1-6的数字！");
            }
        }
    }

    public void listPlayingMovies() {
        System.out.println("\n=======正在上映影片========");
        List<Movie> allMovies = Movie.getAllMovies();
        if (allMovies.isEmpty()) {
            System.out.println("当前无正在上映的影片");
            return;
        }
        for (Movie movie : allMovies) {
            if (movie.isShowing()) {
                System.out.println("片名：" + movie.getName());
                System.out.println("导演：" + movie.getDirector());
                System.out.println("主演：" + movie.getActor());
                System.out.println("时长：" + movie.getDuration() + "分钟");
                System.out.println("评分：" + movie.getScore() + "/10分");
                System.out.println("剧情简介：" + movie.getIntroduction());
                System.out.println("------------------------");
            }
        }
        Log.info(getUserName(), "查询影片", "查看正在上映影片列表");
    }

    public void listShows() {
        System.out.println("\n=======场次查询========");
        System.out.println("1. 当日场次  2. 近3日场次  3. 近一周场次");
        System.out.print("请选择查询范围（1-3）：");
        int days;
        try {
            int rangeChoice = Integer.parseInt(scanner.next().trim());
            days = switch (rangeChoice) {
                case 1 -> 1;
                case 2 -> 3;
                case 3 -> 7;
                default -> {
                    System.out.println("输入无效，默认查询近一周场次");
                    yield 7;
                }
            };
        } catch (NumberFormatException e) {
            System.out.println("输入错误，默认查询近一周场次");
            days = 7;
            Log.error(getUserName(), "场次查询", e);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date now = new Date();
        long maxTime = now.getTime() + days * 24 * 60 * 60 * 1000L;
        System.out.println("\n=======近" + days + "日场次信息========");
        boolean hasShows = false;

        for (Show show : Show.getAllShows()) {
            Date showTime = show.getShowTime();
            if (showTime != null && showTime.getTime() <= maxTime && showTime.getTime() >= now.getTime()) {
                hasShows = true;
                System.out.println("场次ID：" + show.getShowId());
                System.out.println("影片：" + show.getMovie().getName());
                System.out.println("放映厅：" + show.getHall().getHallName());
                System.out.println("时间：" + sdf.format(showTime));
                System.out.println("票价：" + show.getPrice() + "元");
                System.out.println("------------------------");
            }
        }
        if (!hasShows) {
            System.out.println("未查询到符合条件的场次");
        }
        Log.info(getUserName(), "查询场次", "查询近" + days + "日场次");
    }
    public void sellTicket() {
        System.out.println("\n=======售票操作========");
        System.out.print("请输入场次ID：");
        String showId = scanner.next().trim();
        Show targetShow = Show.findShowById(showId);
        if (targetShow == null) {
            System.out.println("未找到该场次");
            return;
        }
        Hall hall = targetShow.getHall();
        Movie movie = targetShow.getMovie();
        for (Seat seat : hall.getSeats()) {
            if (!seat.getShowId().equals(showId)) {
                System.out.println("场次座位未初始化，请联系管理员");
                Log.error(getUserName(), "售票失败", new RuntimeException("场次" + showId + "座位未初始化"));
                return;
            }
        }
        System.out.println("影片：《" + movie.getName() + "》");
        System.out.println("放映时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm").format(targetShow.getShowTime()));
        System.out.println("放映厅：" + hall.getHallName());
        System.out.println("原价：" + targetShow.getPrice() + "元/张");
        System.out.println("\n【座位图】（O=空闲，X=已售）");
        hall.printSeatMap();
        System.out.print("\n请输入购票座位（格式：排数 起始列 结束列，如3 5 7）：");
        int row, startCol, endCol;
        try {
            row = scanner.nextInt();
            startCol = scanner.nextInt();
            endCol = scanner.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("输入格式错误，请输入数字！");
            scanner.nextLine();
            Log.error(getUserName(), "售票-座位输入", e);
            return;
        }

        if (row < 1 || row > hall.getTotalRows()
                || startCol < 1 || endCol > hall.getSeatsPerRow()
                || startCol > endCol) {
            System.out.println("座位选择无效（超出范围或起始列大于结束列）");
            return;
        }

        List<Seat> selectedSeats = new ArrayList<>();
        for (int col = startCol; col <= endCol; col++) {
            Seat seat = hall.getSeat(row, col);
            if (seat == null || seat.isSold()) {
                System.out.println("座位" + row + "排" + col + "座已售出或无效，请重新选择");
                return;
            }
            selectedSeats.add(seat);
        }
        int ticketCount = selectedSeats.size();
        System.out.println("已选择" + ticketCount + "个座位：" + row + "排" + startCol + "-" + endCol + "座");
        System.out.print("是否有儿童票？(y/n)：");
        String hasChild = scanner.next().trim().toLowerCase();
        double childDiscount = 0.5;
        int childCount = 0;
        if (hasChild.equals("y")) {
            System.out.print("请输入儿童数量（不超过总票数）：");
            try {
                childCount = scanner.nextInt();
                if (childCount < 0 || childCount > ticketCount) {
                    System.out.println("儿童数量无效");
                    return;
                }
            } catch (InputMismatchException e) {
                System.out.println("输入错误，请输入数字");
                scanner.nextLine();
                return;
            }
        }
        double total = 0;
        int adultCount = ticketCount - childCount;
        total = (adultCount * targetShow.getPrice()) + (childCount * targetShow.getPrice() * childDiscount);
        System.out.println("成人票" + adultCount + "张，儿童票" + childCount + "张，总价：" + total + "元");

        System.out.print("确认购票？(y/n)：");
        String confirm = scanner.next().trim().toLowerCase();
        if (!confirm.equals("y")) {
            System.out.println("已取消购票");
            return;
        }

        for (Seat seat : selectedSeats) {
            double price = (childCount > 0) ? targetShow.getPrice() * childDiscount : targetShow.getPrice();
            if (childCount > 0) childCount--;
            Ticket ticket = new Ticket(showId, seat, price, getUserName());
            ticketList.add(ticket);
            seat.sell(ticket.getTicketId());
            targetShow.reduceSeats(1);
            ticket.printTicketInfo(targetShow);
        }

        Log.info(getUserName(), "售票成功", "场次：" + showId + "，票数：" + ticketCount);
        System.out.println("售票成功！");
    }

    public void refundTicket() {
        System.out.println("\n=======退票操作========");
        System.out.print("请输入票号：");
        String ticketId = scanner.next().trim();

        Ticket targetTicket = null;
        for (Ticket ticket : ticketList) {
            if (ticket.getTicketId().equals(ticketId) && ticket.getStatus() == 0) {
                targetTicket = ticket;
                break;
            }
        }

        if (targetTicket == null) {
            System.out.println("未找到有效票券");
            return;
        }

        Show show = Show.findShowById(targetTicket.getShowId());
        if (show == null) {
            System.out.println("场次不存在");
            return;
        }

        Date now = new Date();
        long beforeShowTime = show.getShowTime().getTime() - 30 * 60 * 1000L; // 放映前30分钟
        if (now.getTime() > beforeShowTime) {
            System.out.println("已超过退票时间（需在放映前30分钟退票）");
            return;
        }

        if (targetTicket.refund() && targetTicket.getSeat().refund(ticketId)) {
            show.addSeats(1);
            Log.info(getUserName(), "退票成功", "票号：" + ticketId);
            System.out.println("退票成功！");
        } else {
            System.out.println("退票失败");
        }
    }

    public void listSeatInfo() {
        System.out.println("\n=======场次座位信息查询========");
        System.out.print("请输入场次ID：");
        String showId = scanner.next().trim();
        Show show = Show.findShowById(showId);
        if (show == null) {
            System.out.println("未找到该场次");
            return;
        }
        Hall hall = show.getHall();
        System.out.println("影片：《" + show.getMovie().getName() + "》");
        System.out.println("放映时间：" + show.getFormattedShowTime());
        System.out.println("放映厅：" + hall.getHallName());
        System.out.println("总座位数：" + hall.getTotalSeatsCount());
        System.out.println("剩余座位数：" + hall.getAvailableSeatsCount());
        System.out.println("\n【座位图】（O=空闲，X=已售）");
        hall.printSeatMap();
    }
}